package com.csdig.cms.service.impl;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.csdig.cms.common.ConstantDefine;
import com.csdig.cms.common.RealPathResolver;
import com.csdig.cms.dao.CmsSettingDAO;
import com.csdig.cms.dao.ContentImgDAO;
import com.csdig.cms.model.CmsSetting;
import com.csdig.cms.model.ContentImg;
import com.csdig.cms.service.SpiderService;
import com.csdig.cms.utils.DateUtils;

@Service
public class SpiderServiceImpl implements SpiderService {

	@Autowired
	private RealPathResolver pathResolver;

	@Autowired
	private CmsSettingDAO cmsSettingDao;

	@Autowired
	private ContentImgDAO imgDao;

	@Override
	public String replaceImage(String content, String baseUrl, Map<String, String> imgMap) throws Exception {
		Document doc = Jsoup.parse(content, baseUrl);
		Elements images = doc.getElementsByTag("img");
		for (int i = 0; i < images.size(); i++) {
			Element img = images.get(i);
			String imgUrl = img.absUrl("src");
			String domain = getDomain();
			img.attr("src", domain + ConstantDefine.FrontPage.GRAY_IMG);

			List<ContentImg> cimgList = imgDao.findByCovertUrl(imgUrl);
			String fileName = null;
			if (cimgList == null || cimgList.size() == 0) {
				fileName = saveImage(imgUrl, baseUrl, domain);
			} else {
				fileName = cimgList.get(0).getConvertUrl();
			}
			img.attr("data-original", fileName);
			imgMap.put(imgUrl, fileName);
		}
		return doc.body().html();
	}

	@Override
	public String saveImage(String imgUrl, String refer, String domain) throws Exception {
		HttpClient client = new HttpClient();
		GetMethod get = new GetMethod(imgUrl);
		get.addRequestHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");
		get.addRequestHeader("Referer", refer);
		String ext = getExtention(imgUrl);

		String uploadDirPath = pathResolver.get(ConstantDefine.FrontPage.ROOT_RES_DIR + "/upload/");
		File uploadDir = new File(uploadDirPath, DateUtils.getSysDate());
		if (!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
		uploadDirPath = uploadDir.getPath();
		String fileName = System.currentTimeMillis() + "." + ext;
		String result = ConstantDefine.FrontPage.ROOT_RES_DIR + "/upload/" + DateUtils.getSysDate() + "/" + fileName;

		try {
			int sts = client.executeMethod(get);
			if (sts == HttpStatus.SC_OK) {
				File f = new File(uploadDirPath, fileName);
				FileUtils.copyInputStreamToFile(get.getResponseBodyAsStream(), f);
			} else {
				return imgUrl;
			}
		} catch (Exception e) {
			return imgUrl;
		} finally {
			get.releaseConnection();
		}
		return domain + result;
	}

	@Override
	public String getDomain() throws Exception {
		List<CmsSetting> list = cmsSettingDao.findAllFromCache();
		if (list != null && list.size() > 0) {
			for (CmsSetting setting : list) {
				if (StringUtils.equals(setting.getName(), "domain")) {
					return setting.getValue();
				}
			}
		}
		return "";
	}

	private String getExtention(String imgUrl) {
		int idx = imgUrl.lastIndexOf('.');
		return imgUrl.substring(idx + 1);
	}

}
